package server.data;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import server.AuctionManager;

/**
 * Represents a Group Bid
 * @author Group 95
 */
public class GroupBid extends Bid
{
    private Confirmation[] confirmers;
    private boolean finished;

    final public static String USAGE="Invalid parameters, Usage: !groupBid <auction-id> <amount>!";
    final public static String INV_PARAMETERS="Invalid parameters, both have to be numeric!";
    
    public GroupBid(final String[] strParts, final User bidder) throws InvalidCommandException
    {
        super(strParts,bidder);
        this.confirmers=new Confirmation[2];
        this.finished=false;
    }
    
    @Override
    protected String getErrorMessage(final Throwable cause)
    {
        String strRet=null;
        if(cause instanceof IndexOutOfBoundsException)
        {
            strRet = USAGE;
        }
        else if((cause instanceof NumberFormatException) || (cause instanceof ParseException))
        {
            strRet = INV_PARAMETERS;
        }
        return strRet;
    }    
    
    /**
     * Makes a commit on the group Bid
     * @param commiter
     * @return false if the commiter has already commited before or if there are already 2 commiters
     */
    public boolean addConfirmation(final Confirmation confirmation)
    {
        boolean bRet=false;
        if(confirmers[0]==null)
        {
            confirmers[0]=confirmation;
            bRet=true;
        }
        else if((!(confirmers[0]).equals(confirmation)) && (confirmers[1]==null))
        {
            confirmers[1]=confirmation;
            bRet=true;
        }
        return bRet;
    }
    
    /**
     * Returns true if the GroupBid is tentative (has not got 2 commiters)
     * @return true if GroupBid is tentative
     */
    public boolean isTentative()
    {
        return confirmers[1]==null;
    }
    
    /**
     * Returns all Users which partizipated on the GroupBid (as creator or commiter)
     * @return List of Users
     */
    public List<User> getUsers()
    {
        List<User> arRet=new ArrayList<User>();
        arRet.add(this.getBidder());
        for(int i=0;i<confirmers.length;i++)
        {
            if(confirmers[i]!=null)
            {
                arRet.add(confirmers[i].getConfirmer());
            }
        }
        return arRet;
    }

    public boolean isFinished() {
        return finished;
    }

    public void setFinished(boolean finished) {
        this.finished = finished;
    }
    
    
    @Override
    public String toString()
    {
        StringBuilder strB=new StringBuilder(Long.toString(this.getAuctionId())).append(' ');
        strB.append(AuctionManager.getInstance().formatDouble(this.getdPrice())).append(' ');
        strB.append(this.getBidder());
        return strB.toString();
    }
}
